<template>
  <!-- // 分配角色 -->
  <div>
    <el-tree
      ref="treeRef"
      :data="PermissionList"
      :props="{label:'name'}"
      default-expand-all
      :show-checkbox="true"
      :check-strictly="true"
      node-key="id"
    />
    <div style="margin-top: 20px; text-align: right">
      <el-button type="primary" @click="hSubmit">确定</el-button>
      <el-button @click="hClose">取消</el-button>
    </div>
  </div>
</template>
<script>
import { getPermissionList } from '@/api/permissions'
import { tranListToTreeData } from '@/utils'
import { getRoleDetail, assignPerm } from '@/api/settings'
export default {
  props: {
    curId: {
      required: true,
      type: String
    }
  },
  data() {
    return {
      PermissionList: [],
      permIds: []
    }
  },
  created() {
    this.loadPermissionList()
    this.loadPermissionDetail()
  },
  methods: {
    async doSave() {
      try {
        const permIds = this.$refs.treeRef.getCheckedKeys()
        console.log(permIds, 'permIds')
        const res = await assignPerm({ id: this.curId, permIds: permIds })
        console.log(res, 'assignPerm')
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 获取当前角色的权限列表
    async loadPermissionDetail() {
      try {
        const res = await getRoleDetail(this.curId)
        console.log(res, 'getRoleDetail')
        this.permIds = res.data.permIds
        // 回填
        this.$refs.treeRef.setCheckedKeys(this.permIds)
      } catch (error) {
        console.log(error, 'getRoleDetail')
      }
    },
    // 加载权限列表
    async loadPermissionList() {
      try {
        const res = await getPermissionList()
        console.log('getPermissionList', res)
        // this.PermissionList = res.data
        this.PermissionList = tranListToTreeData(res.data)
      // 保存数据
      } catch (err) {
        console.log('err', err)
      }
    },
    hSubmit() {
      // this.$emit('close')
      this.doSave()
    },
    hClose() {
      this.$emit('close')
    }
  }
}
</script>
